package com.lagou.concurrent.demo;

public class NumberResource {
    private Integer number = 0;
    private Integer printIndex = 0;

    private Object myLock = new Object();

    private void add() {
        this.number++;
    }

    private Integer get() {
        return this.number;
    }

//    public synchronized void showNumber() throws InterruptedException {
//        // 大概打印100次，退出虚拟机
//        if (printIndex > 100) System.exit(0);
//
//        Integer number1 = this.get();
//        this.add();
//        Thread.sleep(5);
//
//        Integer number2 = this.get();
//
//        if ((number1 + 1) == number2) {
//            System.out.println(Thread.currentThread().getName() + " => 递增--正确--：" + number1 + " ***** " + number2);
//        } else {
//            System.out.println(Thread.currentThread().getName() + " => 递增**异常**：" + number1 + " ***** " + number2);
//        }
//        // 增加计数
//        printIndex++;
//    }

    public void showNumber() throws InterruptedException {
        synchronized (myLock) {
            // 大概打印100次，退出虚拟机
            if (printIndex > 100) System.exit(0);

            Integer number1 = this.get();
            this.add();
            Thread.sleep(5);

            Integer number2 = this.get();

            if ((number1 + 1) == number2) {
                System.out.println(Thread.currentThread().getName() + " => 递增--正确--：" + number1 + " ***** " + number2);
            } else {
                System.out.println(Thread.currentThread().getName() + " => 递增**异常**：" + number1 + " ***** " + number2);
            }
            // 增加计数
            printIndex++;
        }
    }
}
